package com.haierp.weixin;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.mysql.jdbc.Connection;
import org.apache.commons.io.FileUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JustTest implements ActionListener {
    String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
    String accessKeyId = "LTAIVI0EwNcDNmUe";
    String accessKeySecret = "hFBvxmCDoX5XOZALYENHjl4Q7I8Hsl";
    String bucketName = "wxmessage";
    private OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    String urlhead = "http://" + bucketName + ".oss-cn-hangzhou.aliyuncs.com/";
    private String filePathStr = "";
    JFrame frame = new JFrame("微信聊天导出工具");// 框架布局
    JTabbedPane tabPane = new JTabbedPane();// 选项卡布局
    Container con = new Container();//
    JLabel label1 = new JLabel("文件目录");
    JTextField text1 = new JTextField();// TextField 目录的路径
    JButton button1 = new JButton("选择");// 选择
    JFileChooser jfc = new JFileChooser();// 文件选择器
    JButton button3 = new JButton("确定");//
    JLabel textLabel = new JLabel();
    Connection connection;

    JustTest() throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        connection = (Connection) DriverManager.getConnection("jdbc:mysql://116.62.67.201:3306/haidb?characterEncoding=utf-8&useServerPrepStmts=false&rewriteBatchedStatements=true","haihai", "2018@)!(Iruha");
        connection.setAutoCommit(false);

        jfc.setCurrentDirectory(new File("d://"));// 文件选择器的初始目录定为d盘
        double lx = Toolkit.getDefaultToolkit().getScreenSize().getWidth();

        double ly = Toolkit.getDefaultToolkit().getScreenSize().getHeight();
        frame.setLocation(new Point((int) (lx / 2) - 150, (int) (ly / 2) - 150));// 设定窗口出现位置
        frame.setSize(580, 300);// 设定窗口大小
        frame.setContentPane(tabPane);// 设置布局
        label1.setBounds(20, 10, 70, 20);
        text1.setBounds(80, 10, 300, 20);
        button1.setBounds(400, 10, 80, 20);
        button3.setBounds(260, 50, 60, 20);
        button1.addActionListener(this); // 添加事件处理
        button3.addActionListener(this); // 添加事件处理
        con.add(label1);
        con.add(text1);
        con.add(button1);
        con.add(button3);
        frame.setVisible(true);// 窗口可见
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 使能关闭窗口，结束程序
        tabPane.add("first", con);// 添加布局1

        textLabel.setText("还没执行...");
        JScrollPane scrollPane = new JScrollPane(textLabel);
        scrollPane.setBounds(40,50,130,20);
        con.add(scrollPane);
    }
    /**
     * 时间监听的方法
     */
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        if (e.getSource().equals(button1)) {// 判断触发方法的按钮是哪个
            jfc.setFileSelectionMode(1);// 设定只能选择到文件夹
            int state = jfc.showOpenDialog(null);// 此句是打开文件选择器界面的触发语句
            if (state == 1) {
                return;
            } else {
                File f = jfc.getSelectedFile();// f为选择到的目录
                filePathStr = f.getAbsolutePath();
                text1.setText(f.getAbsolutePath());
            }
        }
        if (e.getSource().equals(button3)) {

            try {
                incomingGroupRecord(filePathStr);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            JOptionPane.showMessageDialog(con, "已完成", "提示", 2);
        }
    }
    public static void main(String[] args) throws Exception {
        new JustTest();
    }

    public void incomingGroupRecord(String filePath) throws Exception {
        String str = null;
        //String pathStr = filePath+"aaa_第"+index+"页.html";
        //System.out.println(filePath);
        File dirFile =  new File(filePath);
        File[] fileList = dirFile.listFiles();
        for (File file : fileList) {
            if (file.isDirectory()) {
                continue;
            }
            //long startTime = System.currentTimeMillis();    //获取开始时间

            try {
                str = FileUtils.readFileToString(file, "UTF-8");
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Document doc = Jsoup.parse(str);
            //System.out.println(doc.toString());
            Elements content = doc.select("div.chatItemContent");
            List<WxMessageItem> list = new ArrayList<WxMessageItem>();
            for (Element link : content) {
                WxMessageItem wxMessageItem = new WxMessageItem();
                String timeStr = null;
                Elements times = link.getElementsByClass("timeyou");
                Date d = null;
                Element time = times.get(0);
                timeStr = time.text();
                textLabel.setText(timeStr);
                textLabel.paintImmediately(textLabel.getBounds());
                //Thread.sleep(10);
                try {
                    d = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(timeStr);
                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                wxMessageItem.setSendTime(d);

                Elements clouds = link.getElementsByClass("cloudContent");
                Element cloud = clouds.get(0);
                String cloudStr = cloud.text();
                Elements srcs =  cloud.getElementsByTag("img");
                String imgSrcStr = "";
                for (int i  = 0  ; i < srcs.size(); i++ ) {
                    String temp = srcs.get(i).attr("src")+" ";
                    imgSrcStr = temp+imgSrcStr;
                }
                String message = cloudStr+imgSrcStr;
                if (!message.contains("：")) {
                    wxMessageItem.setMessageContent(emojiFilter(message));
                    wxMessageItem.setGmtCreate(new Date());
                    wxMessageItem.setGmtModify(new Date());
                } else {
                    String name = message.substring(0,message.indexOf("："));
                    String msgContent = message.substring(message.indexOf("：")+1,message.length());
                    if (msgContent.contains("Img")) {
                        msgContent.trim();
                        //msgContent = uploadImg(filePath+"\\"+msgContent, String.valueOf(d.getTime()));
                        wxMessageItem.setMessageType("picture");
                    }
                    wxMessageItem.setFromUserName(emojiFilter(name));
                    wxMessageItem.setMessageContent(emojiFilter(msgContent));
                    wxMessageItem.setGmtCreate(new Date());
                    wxMessageItem.setGmtModify(new Date());
                }
                Integer id = selectMessage(timeStr);
                if(id == null) {
                    if (wxMessageItem.getMessageType() == "picture") {
                        String msgContent = uploadImg(filePath+"\\"+wxMessageItem.getMessageContent(), String.valueOf(d.getTime()));
                        wxMessageItem.setMessageContent(msgContent);
                    }
                    list.add(wxMessageItem);
                } else {
                    //System.out.println(id);
                }
            }
            if(list.size() >0 ) {
               insertBatch(list);
            }
            long endTime = System.currentTimeMillis();    //获取结束时间
            //System.out.println("程序运行时间：" + (endTime - startTime) + "ms");    //输出程序运行时间
        }
    }

    public Integer selectMessage(String sendTime) throws Exception {
            PreparedStatement cmd = connection
                    .prepareStatement("select id from wx_message_list WHERE send_time = ?");
            cmd.setString(1,sendTime);
            ResultSet rs = cmd.executeQuery();
            Integer id = null;
            while (rs.next()) {
                id = rs.getInt("id");
                //System.out.println(id);
            }
            rs.close();
            cmd.close();
        return id;
    }

    public void insertBatch(List<WxMessageItem> list) throws Exception {
        PreparedStatement cmd = connection
                    .prepareStatement("insert into wx_message_list (message_id,message_type,message_content,from_user_name,to_user_name,is_frient,login_nick,send_time,is_sign,gmt_create,gmt_modify) values(?,?,?,?,?,?,?,?,?,?,?)");
        for (WxMessageItem wx:list) {
            cmd.setString(1,wx.getMessageId());
            cmd.setString(2,wx.getMessageType());
            cmd.setString(3,wx.getMessageContent());
            cmd.setString(4,wx.getFromUserName());
            cmd.setString(5,wx.getToUserName());
            cmd.setString(6,wx.getIsFrient());
            cmd.setString(7,wx.getLoginNick());
            cmd.setTimestamp(8,new Timestamp(wx.getSendTime().getTime()));
            cmd.setInt(9,0);
            cmd.setTimestamp(10,new Timestamp(wx.getGmtCreate().getTime()));
            cmd.setTimestamp(11,new Timestamp(wx.getGmtModify().getTime()));
            cmd.addBatch();
        }
        cmd.executeBatch();
        connection.commit();
        cmd.close();
    }

    public String uploadImg(String path , String key) throws FileNotFoundException {
        File file = new File(path);
        InputStream inputStream = new FileInputStream(file);
        ObjectMetadata objectMeta = new ObjectMetadata();
//      objectMeta.setContentLength(inputStream.);
        objectMeta.setContentType("image/jpeg");
        ossClient.putObject(bucketName, key, inputStream,objectMeta);
        return urlhead+key;
    }

    public String emojiFilter(String str) {
        if (str.trim().isEmpty()) {
            return str;
        }
        String pattern = "[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]";
        String reStr = "";
        Pattern emoji = Pattern.compile(pattern);
        Matcher emojiMatcher = emoji.matcher(str);
        str = emojiMatcher.replaceAll(reStr);
        return str;
    }
}
